﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;

namespace PortalCurriculo.Domain
{
    public class Context
    {
        private static PortalCurriculoEntities instance = null;
        private static object Padlock = new object();

        /// <summary>
        /// Instancia estática do Contexto de entidades
        /// </summary>
        public static PortalCurriculoEntities Instance
        {
            get
            {
                lock (Padlock)
                {
                    return instance ?? (instance = new PortalCurriculoEntities());
                }
            }
        }

        public static void SaveChanges()
        {
            try
            {
                Instance.SaveChanges();
            }
            catch (Exception e)
            {
                var objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Added);
                foreach (var objectStateEntry in objectStateEntries)
                    Instance.Detach(objectStateEntry.Entity);
                objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Modified);
                foreach (var objectStateEntry in objectStateEntries)
                    Instance.Detach(objectStateEntry.Entity);
                objectStateEntries = Instance.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted);
                foreach (var objectStateEntry in objectStateEntries)
                    Instance.Detach(objectStateEntry.Entity);

                throw e;
            }
        }

        public static void Delete(object entity)
        {
            Instance.DeleteObject(entity);
            SaveChanges();
        }
    }
}